package tr.edu.metu.is550.isell.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import tr.edu.metu.is550.isell.R;
import tr.edu.metu.is550.isell.utils.CryptoUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class LoginActivity extends Activity {


    Button btnLogin;
    EditText txtUserName;
    EditText txtPassword;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        btnLogin = (Button) findViewById(R.id.login_button);
        txtUserName = (EditText) findViewById(R.id.username);
        txtPassword = (EditText) findViewById(R.id.password);

        final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String serverURL = sp.getString("pref_dialog", "NULL");

                DefaultHttpClient client = new DefaultHttpClient();


                HttpGet httpGet = new HttpGet(serverURL + "/user/".concat(txtUserName.getText().toString()).concat("/login"));
                httpGet.setHeader("Authorization", "ISell " + CryptoUtils.encryptAndBase64Encode(getApplicationContext(), txtUserName.getText().toString() + ":" + txtPassword.getText().toString()));

                try {
                    HttpResponse response = client.execute(httpGet);

                    if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
                        throw new RuntimeException("Authentication Failed!");
                    }

                    HttpEntity entity = response.getEntity();

                    SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = defaultSharedPreferences.edit();
                    editor.putBoolean("isLoggedIn", Boolean.TRUE);
                    editor.putString("userName", txtUserName.getText().toString());
                    editor.putString("password", txtPassword.getText().toString());
                    editor.apply();

                    Intent myIntent = new Intent(view.getContext(), MainActivity.class);
                    startActivity(myIntent);


                } catch (Exception e) {
                    Toast toast = Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT);
                    toast.show();
                }


            }
        });

    }


    private static String convertStreamToString(InputStream is) {
        /*
        * To convert the InputStream to String we use the BufferedReader.readLine()
        * method. We iterate until the BufferedReader return null which means
        * there's no more data to read. Each line will appended to a StringBuilder
        * and returned as String.
        */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }


}
